﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Feeds.Interop;
using Orchid.Entity;

namespace Orchid
{
    public class Spider
    {
        /// <summary>
        /// get feeds from feedurl
        /// </summary>
        /// <param name="feedUrl">feed url</param>
        public void Ingest(Uri feedUrl)
        {
            string url = feedUrl.OriginalString;
            IFeed feed;
            FeedsManagerClass fmc = new FeedsManagerClass();
            if (fmc.IsSubscribed(url))
            {
                feed = (IFeed)fmc.GetFeedByUrl(url);
            }
            else
            {
                IFeedFolder rootFolder = (IFeedFolder)fmc.RootFolder;
                feed = (IFeed)rootFolder.CreateFeed(url, url);
            }
            feed.Download();

            OrchidEntities entity = new OrchidEntities();

            using (entity)
            {
                foreach (IFeedItem item in (IFeedsEnum)feed.Items)
                {
                    WebPage page = new WebPage(item.Link);
                    Article article = new Article()
                    {
                        Title = item.Title,
                        Content = page.MainContent,
                        Author = item.Author
                    };
                    entity.AddToArticle(article);
                }
                entity.SaveChanges();
                entity.Connection.Close();
            }
        }
    }
}
